<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span><i class="el-icon-document-remove"></i> 护士站 - 出院申请列表</span>
      </div>
    </template>

    <el-form :inline="true" :model="searchForm" @submit.prevent="handleSearch">
      <el-form-item label="病人姓名">
        <el-input v-model="searchForm.patientName" placeholder="输入病人姓名"></el-input>
      </el-form-item>
      <el-form-item label="医生姓名">
        <el-input v-model="searchForm.doctorName" placeholder="输入申请医生"></el-input>
      </el-form-item>
      <el-form-item label="申请日期">
        <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" v-loading="loading" style="width: 100%">
      <el-table-column prop="id" label="申请ID" width="80" />
      <el-table-column prop="patientName" label="病人姓名" width="120" />
      <el-table-column prop="doctorName" label="申请医生" width="120" />
      <el-table-column prop="roomName" label="所在科室" width="150" />
      <el-table-column prop="oaDate" label="出院申请日期" width="180" />
      <el-table-column prop="oaStatus" label="状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.oaStatus)">
            {{ formatStatus(scope.row.oaStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" min-width="150">
        <template #default="scope">
          <el-button
              v-if="scope.row.oaStatus === 1"
              size="small"
              type="danger"
              @click="handleProcessDischarge(scope.row)"
          >
            办理出院
          </el-button>
          <span v-else>—</span>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        style="margin-top: 20px;"
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
    />
  </el-card>

</template>

<script>
// 引入 Element Plus 的消息提示和确认框
import { ElMessage, ElMessageBox } from 'element-plus';
import {processDischarge, queryRecord} from "../api/discharge.js";


// --- Vue 组件定义 ---
export default {
  name: "DischargeApplicationList",
  // 1. data() 选项
  data() {
    return {
      // 搜索表单
      searchForm: {
        patientName: '',
        doctorName: '',
        dateRange: [] // [startDate, endDate]
      },
      // 表格数据
      tableData: [],
      loading: false,
      // 分页
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
    };
  },

  // 2. methods 选项
  methods: {
    // 获取主列表数据
    async fetchData() {
      const query = {
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        patientName: this.searchForm.patientName,
        doctorName: this.searchForm.doctorName,
        applicationStartDate: this.searchForm.dateRange ? this.searchForm.dateRange[0] : null,
        applicationEndDate: this.searchForm.dateRange ? this.searchForm.dateRange[1] : null,
      };

      // 假设您已有一个后端接口 (POST /discharge/list)
      let {data:data} = await queryRecord(query)
      console.log(data)
      if (data.code == 400){
        ElMessage.warning("未搜索到结果")
        this.tableData = null
      }else {
        this.tableData = data.obj.list;
      }
      this.pagination.total = data.obj.total;
    },

    // 搜索
    handleSearch() {
      this.pagination.pageNum = 1; // 搜索时重置回第一页
      this.fetchData();
    },

    // 重置搜索
    handleReset() {
      this.searchForm.patientName = '';
      this.searchForm.doctorName = '';
      this.searchForm.dateRange = [];
      this.handleSearch();
    },

    // 分页：每页条数变化
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchData();
    },

    // 分页：当前页码变化
    handlePageChange(val) {
      this.pagination.pageNum = val;
      this.fetchData();
    },

    // 格式化状态显示
    formatStatus(status) {
      // 对应 'inpatient_discharge_app' 表的 'oa_status' 字段
      if (status === 0) return '未缴费';
      if (status === 1) return '待确认'; // 待护士办理出院
      if (status === 2) return '已完成'; // 已办理出院
      return '未知';
    },

    // 状态标签样式
    getStatusType(status) {
      if (status === 0) return 'danger'; // 未缴费
      if (status === 1) return 'warning'; // 待确认
      if (status === 2) return 'success'; // 已完成
      return 'info';
    },

    // --- 核心操作方法 (对应需求文档) ---

    // 1. 点击"办理出院"
    handleProcessDischarge(row) {
      // (row 对象现在包含了 patientId, bedId 等所有信息)
      ElMessageBox.confirm(
          `确定要为病人 [${row.patientName}] 办理出院手续吗?`,
          '办理出院确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(async () => {

        // 构造 DTO (只发送需要的数据)
        const requestData = {
          id: row.id,
          patientId: row.patientId,
          bedId: row.bedId,
          doctorId: row.doctorId,
          wardId: row.wardId,
          departmentId: row.departmentId
        };

        try {
          // *** 4. 调用真实的 API (替换 mock) ***
          const { data: response } = await processDischarge(requestData);

          if (response.code === 200) {
            ElMessage.success('办理出院成功!');
            await this.fetchData(); // 刷新列表
          } else {
            ElMessage.error(response.message || '办理出院失败');
          }
        } catch (err) {
          ElMessage.error(err.response?.data?.message || err.message || '办理出院失败');
        }
      }).catch(() => {
        // 用户点击了取消
      });
    }
  },

  // 3. created() 钩子
  created() {
    // 页面加载时自动获取第一页数据
    this.fetchData();
  }
};
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}
.el-form {
  border-bottom: 1px solid var(--el-border-color-light);
  padding-bottom: 10px;
  margin-bottom: 20px;
}
</style>